Skip to content

Conversation

oliveror
Copy link
Member

Behaviour change for the team to agree on: search now matches whole words and word beginnings in title, description, ingredients and tags. Mid-word matches are gone: "cake" no longer finds "pancakes"/"cupcakes"; "chick" still finds "chicken".

Changes

Search (also closes #80)

  • PostgreSQL full-text search on recipes.search_vector (GIN index, config simple) covering title, description, ingredient names and tags. A row trigger on recipes and statement-level triggers on recipe_ingredients/recipe_tags keep it current.
  • Every word must match (in any field) as a word prefix: "chicken rice" finds "Rice with chicken"; "golden saffron" finds a recipe with "Golden" in the title and saffron as an ingredient.
  • The query is built from letters and digits only, so input like soup & or ( can never break the tsquery syntax (unit tests incl. Palačinke, bringebær, sunny-side-up).
  • One row per recipe: no duplicates when several ingredients match, exact counts, unchanged visibility rules. The search placeholder says "Search recipes, ingredients or tags…".
  • Chosen over pg_trgm because it needs no database extension or extra privileges on CI/VM, and TASK.md asks for word search.

Sorting and indexes

  • rating_avg/rating_count cached on recipes, kept in step by a trigger on ratings (covers API, seed and manual SQL); backfilled in the migration. The updated_at trigger now ignores these columns, so rating a recipe does not change its "last updated" time.
  • Partial indexes for category, total time and rating whose order matches each ORDER BY. The row query is skipped when the count is 0.

Scalability evidence

  • npm run db:seed:large -- <n> / -- --remove loads or removes a generated catalogue. Use a separate test database, never production (stated in the script and docs); never run by CI or deploy. Runs VACUUM ANALYZE afterwards.
  • Measured locally on 100 000 recipes (PostgreSQL 16 in Docker, EXPLAIN ANALYZE, median of 3; "before" = old queries with the new indexes dropped, same data):
Query Before After
Highest rated, first page 719 ms 0.2 ms
Quickest, first page 84 ms 0.2 ms
Search count "chicken" 91 ms 11 ms
Search, no matches 352 ms 0.2 ms

Whole GraphQL list requests: 4–25 ms for typical searches/filters/sorts; very common words matching half the catalogue ("butter", 49 000 hits) 70–100 ms because exact counts visit every hit. Details in docs/performance-and-images.md.

On the team review comments: precomputing rating averages was kept because the benchmark shows the per-request aggregation was the slowest query (719 ms → 0.2 ms at 100k). Indexes were added only where EXPLAIN showed sequential scans on the listing queries, not for every query.

Validation

  • npm run check passes (217 unit tests); db:check clean.
  • test:db (12) and test:api (17) against PostgreSQL 16; the new API test covers multi-word, prefix, Unicode, hostile input, ingredient and tag matches, no duplicates, private recipes, ingredient edits updating search, and the rating trigger (incl. unchanged updatedAt).
  • Migration 0005 applied to a database with existing data (backfill verified) and from scratch.

Remaining work

  • Keyset pagination for very deep pages (OFFSET still grows linearly; page 1000 ≈ 26 ms).
  • The empty feature/search-multi-word branch is no longer needed and can be deleted.

AI usage

Written with Claude Code (Anthropic) during the final-delivery review and extended after a teammate's review. Please review the diff as you would any other contribution.

Closes #69
Closes #80

- Search: full-text search on a generated tsvector of title and
  description with a GIN index (config 'simple', no extension needed).
  Every word must match as a word prefix, so "chicken rice" finds
  "Rice with chicken". The query is built from letters and digits only,
  so user input cannot break the tsquery syntax. Behaviour change: words
  no longer match mid-word ("cake" does not find "pancakes").
- Highest rated: rating_avg/rating_count cached on recipes and kept in
  step by a trigger on ratings (covers API, seed and manual SQL); the
  touch trigger now ignores these columns so rating does not change a
  recipe's updated time. Summaries read the cached values.
- Partial indexes for category, total time and rating whose order matches
  each ORDER BY; the row query is skipped when the count is 0.
- npm run db:seed:large -- <n> | --remove loads or removes a generated
  catalogue (never run by CI or deploy).

Measured locally on 100 000 recipes (EXPLAIN ANALYZE, median of 3):
highest rated 439 -> 0.1 ms, quickest 42 -> 0.1 ms, search count
94 -> 10 ms; whole GraphQL list requests 2-29 ms. Numbers and method in
docs/performance-and-images.md.

Closes #69
Closes #80
Following team review: the search document now covers title,
description, ingredient names and tags. search_vector is a plain column
kept current by a row trigger on recipes and statement-level triggers on
recipe_ingredients/recipe_tags, so one search still hits one row per
recipe (no duplicates, exact counts, same visibility rules).

seed-large now runs VACUUM ANALYZE after loading (the triggers leave
dead rows that made counts several times slower). Docs updated with new
measurements and a warning to use a separate test database, never
production.

Refs #69, #80
@oliveror oliveror requested a review from a team as a code owner November 16, 2026 14:05
Copy link
Member

@olestan olestan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes due to a couple of correctness issues that could cause regressions:

  • Concurrent rating deadlocks: rate() uses FOR SHARE, but the new trigger updates the same recipe row. Simultaneous ratings can deadlock and fail. Consider using a stronger lock before writing.
  • Stale cached data: Concurrent rating or ingredient/tag updates can overwrite cached values calculated from outdated snapshots. Serialize updates before recomputing aggregates and search vectors.
  • Incomplete trigger handling: Moving ratings, ingredients, or tags between recipes does not properly refresh both affected recipes, potentially leaving incorrect ratings or search results.
  • Search terms silently ignored: toSearchQuery() limits searches to 8 words without informing users, potentially returning results that don't match the full query.

I'd recommend fixing the concurrency issues before merging and adding regression tests for simultaneous writes.

…arch word

- rate() takes FOR NO KEY UPDATE instead of FOR SHARE: the ratings trigger
  updates the same recipe row, so two shared locks deadlocked.
  removeRating() takes the same lock first, in a transaction.
- The rating and search-vector triggers lock the recipe row(s) (in id order)
  before recomputing, so a concurrent write is counted instead of being
  overwritten from a stale snapshot.
- Moving a rating, ingredient or tag to another recipe refreshes both
  recipes (rating trigger also fires on recipe_id; update triggers use both
  transition tables).
- toSearchQuery() no longer drops words after the eighth; repeated words are
  searched once, and the 200-character input limit bounds the query.
- test:api: concurrent rate/remove through the API, interleaved raw-SQL
  writes on ratings, ingredients and tags, moved rows, and a 9-word search.
@oliveror
Copy link
Member Author

Thanks — all four were real. Fixed in the latest commit:

  • Concurrent rating deadlocks: rate() now takes FOR NO KEY UPDATE on the recipe instead of FOR SHARE. removeRating() takes the same lock first, inside a transaction, so a rate and a remove at the same time can't deadlock either. I reproduced the deadlock first: six users rating one recipe at once returned INTERNAL_SERVER_ERROR before the fix.
  • Stale cached data: both triggers lock the recipe row (or rows, in id order) before recomputing. The aggregate or search document is then built in a new snapshot, so a write that committed in the meantime is counted instead of overwritten. This also covers writes outside the API, such as the seed or manual SQL.
  • Moved rows: the rating trigger now also fires on recipe_id changes and refreshes both the old and the new recipe. The ingredient and tag UPDATE triggers use both the OLD and NEW transition tables.
  • Search terms: toSearchQuery() no longer drops words. Repeated words are searched once, and the existing 200-character limit bounds the query.

New test:api case, run 3 times in a row:

  • Three rounds of concurrent ratings from 6 users, then concurrent rate/remove: no errors, and the count and average are exact.
  • Two deliberately interleaved raw-SQL transactions on ratings, and on ingredients plus tags: the second waits for the first and counts it.
  • Moving a rating, an ingredient and a tag between recipes.
  • A 9-word search whose last word matches nothing returns no results.

npm run check (217 unit tests) and test:api pass.

Note: I edited migration 0005 in place since it isn't merged yet. A local database that already applied the earlier 0005 keeps the old triggers and needs a reset.

@olestan
Copy link
Member

olestan commented Nov 17, 2026

Thanks — all four were real. Fixed in the latest commit:

  • Concurrent rating deadlocks: rate() now takes FOR NO KEY UPDATE on the recipe instead of FOR SHARE. removeRating() takes the same lock first, inside a transaction, so a rate and a remove at the same time can't deadlock either. I reproduced the deadlock first: six users rating one recipe at once returned INTERNAL_SERVER_ERROR before the fix.
  • Stale cached data: both triggers lock the recipe row (or rows, in id order) before recomputing. The aggregate or search document is then built in a new snapshot, so a write that committed in the meantime is counted instead of overwritten. This also covers writes outside the API, such as the seed or manual SQL.
  • Moved rows: the rating trigger now also fires on recipe_id changes and refreshes both the old and the new recipe. The ingredient and tag UPDATE triggers use both the OLD and NEW transition tables.
  • Search terms: toSearchQuery() no longer drops words. Repeated words are searched once, and the existing 200-character limit bounds the query.

New test:api case, run 3 times in a row:

  • Three rounds of concurrent ratings from 6 users, then concurrent rate/remove: no errors, and the count and average are exact.
  • Two deliberately interleaved raw-SQL transactions on ratings, and on ingredients plus tags: the second waits for the first and counts it.
  • Moving a rating, an ingredient and a tag between recipes.
  • A 9-word search whose last word matches nothing returns no results.

npm run check (217 unit tests) and test:api pass.

Note: I edited migration 0005 in place since it isn't merged yet. A local database that already applied the earlier 0005 keeps the old triggers and needs a reset.

The previous issues appear fixed, but a potential deadlock remains: API and direct SQL writes can acquire locks in opposite orders.

Please add a regression test and address this through consistent lock ordering or deadlock retries before merging.

The API locks a recipe before its ratings, ingredients or tags; a write
outside the API (seed, manual SQL) locks the child row first and the
recipe in its trigger, so the two can deadlock. Lock order cannot be
forced on such writers, so transaction() now rolls back and retries a
transaction that fails with 40P01 (deadlock) or 40001 (serialization),
up to three attempts with a short jittered pause.

test:api: a manual session locks a rating, the API rate() then waits for
it while holding the recipe, and the manual update's trigger waits for
the recipe. Before this change the API returned "deadlock detected"; now
it retries, succeeds, and the cached rating counts both writes.

Refs #69
@oliveror
Copy link
Member Author

Thanks, confirmed. I reproduced it as a test first, then fixed it in 3a239f0.

The deadlock: the API locks the recipe and then a rating, ingredient or tag. A write outside the API (seed, manual SQL) locks the child row first, and its trigger then locks the recipe. Two such transactions can each wait for the other.

Fix: deadlock retries. transaction() in recipeRepository.ts now rolls back and reruns a transaction that fails with 40P01 (deadlock) or 40001 (serialization failure). It tries at most three times, with a short random pause between attempts. This covers every API write path (rate, removeRating, update, delete, save, create). I didn't try to force a single lock order: an outside writer can't be made to lock the recipe before the child row it updates, because PostgreSQL locks that row before any trigger runs.

Regression test (test:api):

  1. A manual SQL session locks a rating (SELECT … FOR UPDATE).
  2. The API rateRecipe locks the recipe and waits for that rating. The test waits until pg_blocking_pids shows this.
  3. The manual UPDATE of the rating then fires its trigger, which waits for the recipe.

On the previous commit the API returns deadlock detected and the test fails. With the retry it succeeds, and the cached count and average include both writes.

One remaining case: PostgreSQL aborts whichever side's deadlock check runs first. Usually that's the side that started waiting first. If that is the outside session, it gets the deadlock error. The seed and manual SQL should retry, or run when the API is idle. I don't think the API should depend on that.

I also merged the latest dev into this branch. The only conflict was the README's known limitations: I kept the persistent-drafts line from dev and dropped "Seed does not demonstrate performance", which this PR makes obsolete.

npm run check (277 unit tests), test:db (12) and test:api (18) pass against PostgreSQL 16.

@oliveror oliveror merged commit 2dc2c2d into dev Nov 17, 2026
2 checks passed
@oliveror oliveror deleted the feature/search-scalability branch November 20, 2026 15:31
Sign in to join this conversation on GitHub.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants